package com.palm.hubo2o.network;

import android.app.Activity;
import android.widget.Toast;

import com.palm.hubo2o.PalmApplication;
import com.palm.hubo2o.R;
import com.palm.hubo2o.ui.LoginActivity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by wongqi on 16/6/14.
 */
public abstract class PalmCallBack<T> implements Callback<Result<T>> {
    private final int hashCode;
    private final PalmApplication mApplication;

    public PalmCallBack(Activity activity) {
        mApplication = (PalmApplication) activity.getApplicationContext();
        hashCode = activity.hashCode();
    }

    @Override
    public void onResponse(Call<Result<T>> call, Response<Result<T>> response) {
        if (response.isSuccessful()) {
            if (response.body().isSuccessful()) {
                succeed(response.body().getBody());
            } else {
                if ("-999".equals(response.body().getStatusCode()) && !(mApplication.getTopActivity() instanceof LoginActivity)) {//登录失效
                    PalmSession.logout();
                    Activity a = mApplication.findActivityByHashCode(hashCode);
                    if (a != null) {
                        Toast.makeText(a, R.string.prompt_login_invalid, Toast.LENGTH_SHORT).show();
                        PalmSession.login(a);
                    }
                }
                failed(response.body().getMessage());
            }
        } else {
            failed(response.message());
        }

    }


    @Override
    public void onFailure(Call<Result<T>> call, Throwable t) {
        failed(t.getClass().getName());
    }

    public abstract void succeed(T t);

    public abstract void failed(String message);
}
